import re
from subprocess import call
import os
import sys
argv = sys.argv
REGEX = "https?:\/\/steamcommunity.com\/sharedfiles\/filedetails\/\?id=[0-9]+.*"  #just * for now
ID_RE = "[0-9]{4,}"


# Globals
STEAMCMD_LOC = "./steamcmd.sh"


# Functions
def extract_mods_ids(FILENAME):
    list_of_links = []
    list_of_ids = set() 
    with open(FILENAME, "r" ) as f:
        list_of_links = f.readlines()
    for link in list_of_links:
        # Remove \n \r
        link = link.rstrip() 
        # If link is valid
        if(re.search(REGEX, link)):
            id_number = re.findall(ID_RE, link)[-1]
            list_of_ids.add(id_number) 
   
    # set removes dublicates
    uniq_qty = 0
    list_of_ids = list(list_of_ids)
    for id_number in list_of_ids:#TESTING
        uniq_qty += 1
        print("unique id number: " + id_number)
    print(f'TOTAL unique ids: {uniq_qty}')
    return list_of_ids


def controll_steamcmd(list_of_ids, APP_ID, DIRECTORY, STEAMCMD_LOC):
    # Steam CMD commandline parametres 
    login_prm = "+login anonymous"
    directory_prm = f"+force_install_dir {DIRECTORY}"
    cmd_prm_list = [STEAMCMD_LOC, login_prm, directory_prm]

    downnload_cmd = f"+workshop_download_item {APP_ID}"  
    for id_number in list_of_ids:
        #print("unique id number " + id_number)
        cmd_prm_list.append(downnload_cmd + " " + id_number) 

    cmd_prm_list.append("+quit") 
    print(cmd_prm_list)
    try:
        call(cmd_prm_list)
    except FileNotFoundError:
        print(f"[Errno 2] No such file or directory: '{STEAMCMD_LOC}'")
        print(f"Put inside the folder with the {STEAMCMD_LOC}")
        sys.exit(0)


# Main Function
def main():
    print(f"Put inside the folder with the {STEAMCMD_LOC}")

    if len(argv)!= 4:
        print("Usage: programm_name <path_to_a_file/filename with the mod links> <numeric_steam_app_id> <mods_destination_folder_loc>")
        sys.exit(0)

    FILENAME = argv[1]
    APP_ID = argv[2]
    DIRECTORY = argv[3]

    if(os.path.isfile(FILENAME) != True):
        print("File do not exist")
        print("Usage: programm_name <path_to_a_file/filename with the mod links> <numeric_steam_app_id> <mods_destination_folder_loc>")
        sys.exit(0)

    #steamcmd +login anonymous +force_install_dir ../czero 
    list_of_ids = extract_mods_ids(FILENAME)
    controll_steamcmd(list_of_ids, APP_ID, DIRECTORY, STEAMCMD_LOC)

try:
    main()
except KeyboardInterrupt:
    print("\nInterrupted, exiting")
    sys.exit(0)





